/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui;

import bean.Horarios;
import controlador.ControladorHorarios;
import java.sql.Time;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.RollbackException;
import javax.swing.JOptionPane;

import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Júnior
 */
public class PainelHorario extends javax.swing.JPanel {

    /**
     * Creates new form PainelHorario
     */
    DefaultTableModel tabelaHoraDasAulas = new DefaultTableModel(new String[]{"Código", "Hora Inicial", "Hora Final", "Turno"}, 0) {
        @Override
        public boolean isCellEditable(int row, int column) {
            return false;
        }
    };

    public PainelHorario() {
        initComponents();
        preencheTabela();

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel5 = new javax.swing.JLabel();
        jComboBoxTurno = new javax.swing.JComboBox();
        jPanelBotoes = new javax.swing.JPanel();
        jButtonNovo = new javax.swing.JButton();
        jButtonSalvar = new javax.swing.JButton();
        jButtonExcluir = new javax.swing.JButton();
        jTextFieldInicio = new javax.swing.JFormattedTextField();
        jTextFieldFinal = new javax.swing.JFormattedTextField();
        jTextFieldCodigo = new javax.swing.JFormattedTextField();

        setMaximumSize(new java.awt.Dimension(830, 512));
        setMinimumSize(new java.awt.Dimension(830, 512));
        setPreferredSize(new java.awt.Dimension(830, 512));

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Horário das Aulas");

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel2.setText("Código :");

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel3.setText("Hora Inicial :");

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel4.setText("Hora Final :");

        jTable1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jTable1.setModel(tabelaHoraDasAulas);
        jTable1.getTableHeader().setReorderingAllowed(false);
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jLabel5.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel5.setText("Turno :");

        jComboBoxTurno.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jComboBoxTurno.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Manhã", "Tarde", "Noite" }));

        jPanelBotoes.setLayout(new java.awt.GridBagLayout());

        jButtonNovo.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jButtonNovo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/Copy.png"))); // NOI18N
        jButtonNovo.setText("Novo");
        jButtonNovo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonNovoActionPerformed(evt);
            }
        });
        jPanelBotoes.add(jButtonNovo, new java.awt.GridBagConstraints());

        jButtonSalvar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jButtonSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/Add.png"))); // NOI18N
        jButtonSalvar.setText("Salvar");
        jButtonSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSalvarActionPerformed(evt);
            }
        });
        jPanelBotoes.add(jButtonSalvar, new java.awt.GridBagConstraints());

        jButtonExcluir.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jButtonExcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/Delete.png"))); // NOI18N
        jButtonExcluir.setText("Excluir");
        jButtonExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonExcluirActionPerformed(evt);
            }
        });
        jPanelBotoes.add(jButtonExcluir, new java.awt.GridBagConstraints());

        try {
            jTextFieldInicio.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##:##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jTextFieldInicio.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        jTextFieldInicio.setText("0000");
        jTextFieldInicio.setToolTipText("");
        jTextFieldInicio.setCaretPosition(0);
        jTextFieldInicio.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR));
        jTextFieldInicio.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

        try {
            jTextFieldFinal.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##:##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jTextFieldFinal.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        jTextFieldFinal.setText("0000");
        jTextFieldFinal.setCaretPosition(0);
        jTextFieldFinal.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

        jTextFieldCodigo.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0"))));
        jTextFieldCodigo.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        jTextFieldCodigo.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 830, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(jPanelBotoes, javax.swing.GroupLayout.PREFERRED_SIZE, 830, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextFieldCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel3)
                        .addGap(4, 4, 4)
                        .addComponent(jTextFieldInicio, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(4, 4, 4)
                        .addComponent(jLabel4)
                        .addGap(4, 4, 4)
                        .addComponent(jTextFieldFinal, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(4, 4, 4)
                        .addComponent(jLabel5)
                        .addGap(4, 4, 4)
                        .addComponent(jComboBoxTurno, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 808, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel2)
                        .addComponent(jTextFieldCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jTextFieldInicio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextFieldFinal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jComboBoxTurno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(3, 3, 3)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4)
                            .addComponent(jLabel5))))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 341, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanelBotoes, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonNovoActionPerformed
        limpacampos();

    }//GEN-LAST:event_jButtonNovoActionPerformed

    private void jButtonSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSalvarActionPerformed
        if (jTextFieldCodigo.getText().equals("") || jTextFieldInicio.getText().equals("") || jTextFieldFinal.getText().equals("")) {
            JOptionPane.showMessageDialog(null, "Obrigatório preencher todos os campos");
        } else {
            Horarios horario = new Horarios();
            horario.setCodHorario(Integer.parseInt(jTextFieldCodigo.getText()));

            /* SimpleDateFormat formatador = new SimpleDateFormat("HH:mm");
             Date data1,data2;
            
             try {
             data1 = (Date) formatador.parse(jTextFieldInicio.getText());
             Time time1 = new Time(data1.getTime()); 
             horario.setInicio(time1);
             data2 = (Date) formatador.parse(jTextFieldFinal.getText());
             Time time2 = new Time(data2.getTime()); 
             horario.setFim(time2);
             } catch (ParseException ex) {
             Logger.getLogger(PainelHorario.class.getName()).log(Level.SEVERE, null, ex);
             }*/
            SimpleDateFormat formato = new SimpleDateFormat("HH:mm");

            Time hora1 = null, hora2 = null;
            try {
                hora1 = new java.sql.Time(formato.parse(jTextFieldInicio.getText()).getTime());
                hora2 = new java.sql.Time(formato.parse(jTextFieldFinal.getText()).getTime());
            } catch (ParseException ex) {
                Logger.getLogger(PainelHorario.class.getName()).log(Level.SEVERE, null, ex);
            }

            horario.setInicio(hora1);
            horario.setFim(hora2);

            int opcao = jComboBoxTurno.getSelectedIndex();
            if (opcao == 0) {
                horario.setTurno("M");
            } else if (opcao == 1) {
                horario.setTurno("T");
            } else {
                horario.setTurno("N");
            }
            ControladorHorarios ch = new ControladorHorarios();
            ch.salva(horario);
            preencheTabela();
        }
    }//GEN-LAST:event_jButtonSalvarActionPerformed

    private void jButtonExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonExcluirActionPerformed
        ControladorHorarios ch = new ControladorHorarios();
        if (jTextFieldCodigo.getText().equals("")) {
            JOptionPane.showMessageDialog(null, "Clique em uma linha ou informe o código do horário");
        } else {
            int opcao = JOptionPane.showConfirmDialog(null, "Tem certeza da exclusão?", "Excluir", JOptionPane.YES_NO_OPTION);
            if (opcao == JOptionPane.YES_OPTION) {
                try {
                    ch.exclui(Integer.parseInt(jTextFieldCodigo.getText()));
                    preencheTabela();
                    limpacampos();
                } catch (RollbackException e) {
                    JOptionPane.showMessageDialog(null,
                            "Impossível excuir registro, pois está associado no horário de alguma turma");
                }

            } else {
                JOptionPane.showMessageDialog(null,
                        "Registro não excluído");
            }
        }
    }//GEN-LAST:event_jButtonExcluirActionPerformed

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        int linha = jTable1.getSelectedRow();
        jTextFieldCodigo.setText(jTable1.getValueAt(linha, 0).toString());
        jTextFieldInicio.setText(jTable1.getValueAt(linha, 1).toString());
        jTextFieldFinal.setText(jTable1.getValueAt(linha, 2).toString());

        if (jTable1.getValueAt(linha, 3).toString().equals("M")) {
            jComboBoxTurno.setSelectedIndex(0);
        } else if (jTable1.getValueAt(linha, 3).toString().equals("T")) {
            jComboBoxTurno.setSelectedIndex(1);
        } else {
            jComboBoxTurno.setSelectedIndex(2);
        }
    }//GEN-LAST:event_jTable1MouseClicked

    private void preencheTabela() {

        tabelaHoraDasAulas.setNumRows(0);
        ControladorHorarios ch = new ControladorHorarios();
        List<Horarios> lista = ch.lista();
        int t = lista.size();
        for (int i = 0; i < t; i++) {
            Horarios horario = lista.get(i);
            tabelaHoraDasAulas.addRow(new Object[]{horario.getCodHorario(), horario.getInicio(), horario.getFim(), horario.getTurno()});

        }
    }

    private void limpacampos() {
        jTextFieldCodigo.setText("");
        jTextFieldInicio.setText("0000");
        jTextFieldFinal.setText("0000");
        jComboBoxTurno.setSelectedIndex(0);
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonExcluir;
    private javax.swing.JButton jButtonNovo;
    private javax.swing.JButton jButtonSalvar;
    private javax.swing.JComboBox jComboBoxTurno;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanelBotoes;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JFormattedTextField jTextFieldCodigo;
    private javax.swing.JFormattedTextField jTextFieldFinal;
    private javax.swing.JFormattedTextField jTextFieldInicio;
    // End of variables declaration//GEN-END:variables
}
